<template>
    <n-form
        ref="formRef"
        label-placement="top"
        :label-width="80"
        :model="form"
        :rules="rules"
    >
        <n-form-item label="名称" path="name">
            <n-input v-model:value="form.name" placeholder="请输入名称" />
        </n-form-item>
        <n-form-item label="标识Key" path="typeKey">
            <n-input v-model:value="form.typeKey" placeholder="请输入标识Key" />
        </n-form-item>
        <n-form-item label="模式层级" path="modeLevel">
            <n-radio-group v-model:value="form.modeLevel" name="modeLevel">
                <n-space>
                    <n-radio :value="1"> 一级 </n-radio>
                    <n-radio :value="2"> 多级 </n-radio>
                </n-space>
            </n-radio-group>
        </n-form-item>
    </n-form>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import type { FormInst, FormRules } from 'naive-ui'
import { Rules } from '@/utils'
import { JBoltApi } from '@/utils/request'
import { useResetableData } from '@/hooks/common/use-resetable-data'
import { ResData } from '@/typings/request'

const props = withDefaults(
    defineProps<{
        id: string
    }>(),
    {
        id: ''
    }
)

/** 表单相关 start */
const formRef = ref<FormInst | null>()
interface DictionaryType {
    id: string
    name: string
    modeLevel: 1 | 2
    typeKey: string
}
const form = useResetableData<DictionaryType>({
    id: '',
    name: '',
    modeLevel: 1,
    typeKey: ''
})
const rules: FormRules = {
    name: new Rules().required('请输入名称').value,
    typeKey: new Rules().required('请输入标识Key').value
}

/**
 * 提交表单
 */
async function submit() {
    await formRef.value?.validate()

    let url = props.id
        ? '/api/admin/dictionaryType/update'
        : '/api/admin/dictionaryType/save'
    let res = await JBoltApi.tryPost<ResData>(url, form)
    return res.data
}

function loadEditData() {
    JBoltApi.get<ResData>(`/api/admin/dictionaryType/${props.id}`).then(
        ({ error, result }) => {
            if (error) return
            form._reset(result.data)
        }
    )
}

onMounted(() => {
    if (props.id) {
        loadEditData()
    }
})

defineExpose({
    submit
})

/** 表单相关 end */
</script>
<style scoped></style>
